package com.atguigu.gmall.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: 李旭
 * @create: 2021-09-13 14:12
 *
 *   延迟消息  基于死信的
 *
 *   spring.xml
 *   <bean id="exchange" class=org.springframework.amqp.core.DirectExchange></bean>
 *
 **/
@Configuration
public class DeadLetterConfig {

    public static final String exchange_dead = "exchange.dead";
    public static final String routing_dead_1 = "routing.dead.1";
    public static final String routing_dead_2 = "routing.dead.2";
    public static final String queue_dead_1 = "queue.dead.1";
    public static final String queue_dead_2 = "queue.dead.2";

    //发布、订阅模式   交换机与队列之间的RoutingKey  是空格  空串 ""
    //路由模式         交换机与队列之间的RoutingKey  是固定的字符串
    //主题模式         交换机与队列之间的RoutingKey  #.range.*   通配符模式  haha.hehe.range.hoho


    //交换机与死信交换机 合并成一个交换机了  没有区别
    @Bean
    public Exchange deadLetterExchange(){
        return ExchangeBuilder.directExchange(exchange_dead).build();//路由模式下的直接交换机

    }
    //死信列队
    @Bean
    public Queue deadLetterQueue(){
        Map<String, Object> arguments = new HashMap<>();
        //TTL  毫秒  测试   10S
        arguments.put("x-message-ttl",10000);
        //配置死信交换机
        arguments.put("x-dead-letter-exchange",exchange_dead);
        //配置死信RoutingKEy
        arguments.put("x-dead-letter-routing-key",routing_dead_2);
        return QueueBuilder.durable(queue_dead_1).withArguments(arguments).build();
    }
    //普通队列
    @Bean
    public Queue queue(){
        return QueueBuilder.durable(queue_dead_2).build();
    }

    //绑定1
    @Bean
    public Binding bindingDeadLetterQueueToExchange(){
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange())
                .with(routing_dead_1).noargs();
    }
    //绑定2
    @Bean
    public Binding bindingQueueToDeadLetterExchange(){
        return BindingBuilder.bind(queue()).to(deadLetterExchange())
                .with(routing_dead_2).noargs();
    }

    //队列
    @Bean  //将下面的对象加载到SpringIOC容器中去  起名是：delayedQueue
    // <bean id="delayedQueue" class ..>
    public Queue delayedQueue(){
        return QueueBuilder.durable(DelayedConfig.queue_delay_1).build();
    }

}
